import React, { Component } from 'react';
import loading from '../../loading.gif'
import debounce from '../../utils/debounce'
class Index extends Component {
  enterClient = debounce(() => {
    // 获取图片高度
    const imgH = this.img.offsetHeight
    // 获取滚动条滚动距离
    const scrollTop = document.documentElement.scrollTop
    // 视口高度
    const clientHeight = document.documentElement.clientHeight
    // 图片距离顶部位置
    const imgTop = this.img.offsetTop
    // 
    const flag1 = (scrollTop + clientHeight) >= imgTop
    const flag2 = (scrollTop - imgH) <= imgTop
    if (flag1 && flag2) {
      this.img.src = this.props.src
    }
  })
  componentDidMount() {
    this.enterClient()
    document.addEventListener('scroll', this.enterClient)
  }
  componentWillUnmount() {
    document.removeEventListener('scroll', this.enterClient)
  }
  render() {
    return (
      <div>
        <img src={loading} alt="" ref={ref => this.img = ref} height="400" />
      </div>
    );
  }
}

export default Index;
